1
2
3
4
5 package com.jguild.jrpm.io.datatype;
6
7 import java.io.UnsupportedEncodingException;
8
9
10 /***
11 * Misc utilities functions.
12 *
13 * @version $Id: RPMUtil.java,v 1.2 2003/10/20 16:31:38 mkuss Exp $
14 */
15 public class RPMUtil {
16 /*** Default encoding is US-ASCII for normal string in rpm header.
17 * For I18 entries the specified encoding
18 * (as defined in HEADERI18NTABLE) should be user. */
19 private static final String DEFAULT_ENCODING = "US-ASCII";
20
21 /***
22 * Method to get a beautyfied representation of an byte array as a hex string.
23 * One byte will always be displayed as two hex digits.
24 *
25 * @param barray An byte array that should be converted to a hex string
26 *
27 * @return The hex string
28 */
29 public static String byteArrayToHexString(byte[] barray) {
30 StringBuffer buf = new StringBuffer();
31
32 for (int i = 0; i < barray.length; i++) {
33 buf.append(byteToHexString(barray[i]));
34 }
35
36 return buf.toString();
37 }
38
39 /***
40 * Method to get a beautyfied representation of a byte as a hex string.
41 * The hex block will be displayed always as two digits.
42 *
43 * @param b A byte that should be converted to a hex string
44 *
45 * @return The hex string
46 */
47 public static String byteToHexString(byte b) {
48 String hex = Integer.toHexString(0x0FF & b);
49
50 if (hex.length() == 1) {
51 hex = "0" + hex;
52 }
53
54 return hex;
55 }
56
57 /***
58 * Method to convert a null terminated C string into a java
59 * string using the DEFAULT_ENCODING
60 *
61 * @param data An array of bytes containing a C string
62 * @param offset An offset from which to start to read the string from the data array
63 *
64 * @return A java string representig a null terminated C string
65 */
66 public static String cArrayToString(byte[] data, int offset)
67 throws UnsupportedEncodingException {
68 return cArrayToString(data, offset, DEFAULT_ENCODING);
69 }
70
71 /***
72 * Method to convert a null terminated C string into a
73 * java string using the defined encoding
74 *
75 * @param data An array of bytes containing a C string
76 * @param offset An offset from which to start to read the string from the data array
77 * @param enc A encoding as defined in java.lang.String
78 *
79 * @return A java string representig a null terminated C string
80 */
81 public static String cArrayToString(byte[] data, int offset, String enc)
82 throws UnsupportedEncodingException {
83 if (offset > data.length) {
84 throw new IllegalArgumentException("Data offset is too big");
85 }
86
87 for (int i = offset; i < data.length; i++) {
88 if (data[i] == 0) {
89 return new String(data, offset, i - offset, enc);
90 }
91 }
92
93
94 return "";
95 }
96 }